package org.jeecg.modules.vinQuery.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.modules.vinQuery.service.VinQueryService;
import org.jeecg.modules.vinQuery.service.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Api(tags = "vin查询")
@RestController
@RequestMapping("/api/vin")
public class VinQueryController {

    private final VinQueryService vinQueryService;

    @Autowired
    public VinQueryController(VinQueryService vinQueryService) {
        this.vinQueryService = vinQueryService;
    }

    /**
     * 触发查询并返回验证码图片路径。
     */
    @ApiOperation(value = "vin-打开页面", notes = "vin-打开页面")
    @GetMapping("/start")
    public Result<?> startQuery(@RequestParam(name = "openId") String openId) throws Exception {
        String captchaImgPath = vinQueryService.startQueryAndGetCaptcha(openId);
        return Result.OK(captchaImgPath);
    }

    /**
     * 提交验证码并继续执行后续逻辑。
     */
    @ApiOperation(value = "vin-提交查询", notes = "vin-提交查询")
    @PostMapping("/submit")
    public Result<?> submitCaptcha(@RequestParam(name = "openId") String openId,
                                   @RequestParam(name = "vin") String vin,
                                   @RequestParam(name = "engine") String engine,
                                   @RequestParam(name = "captcha") String captcha) throws Exception {
        Map<String, String> result = vinQueryService.submitCaptchaAndFetchResult(openId, vin, engine, captcha);
        return Result.OK(result);
    }

    /**
     * 刷新验证码并返回新的验证码图片路径。
     */
    @ApiOperation(value = "vin-刷新验证码", notes = "vin-刷新验证码")
    @PostMapping("/refreshCaptcha")
    public Result<?> refreshCaptcha(@RequestParam(name = "openId") String openId) throws Exception {
        String newCaptchaPath = vinQueryService.refreshCaptcha(openId);
        return Result.OK(newCaptchaPath);
    }

    /**
     * 清理资源，关闭WebDriver实例。
     */
    @ApiOperation(value = "vin-关闭浏览器", notes = "vin-关闭浏览器")
    @PostMapping("/cleanup")
    public Result<?> cleanup(@RequestParam(name = "openId") String openId) {
        vinQueryService.cleanupResources(openId);
        return Result.OK();
    }

}
